import UIKit

// 定义分类模型
struct Category {
  let name: String
  let contents: [String]
}

// 定义数据源协议
protocol DualListViewControllerDataSource: AnyObject {
  func numberOfCategories() -> Int
  func categoryAt(index: Int) -> Category
}

// 定义点击事件代理协议
protocol DualListViewControllerDelegate: AnyObject {
  func didSelectCategory(at index: Int)
  func didSelectContent(at categoryIndex: Int, contentIndex: Int)
}

class DualListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
  @IBOutlet var categoriesTableView: UITableView!
  @IBOutlet var contentsTableView: UITableView!

  weak var dataSource: DualListViewControllerDataSource?
  weak var delegate: DualListViewControllerDelegate?

  private var selectedCategoryIndex: Int? = 0

  override func viewDidLoad() {
    super.viewDidLoad()
    categoriesTableView.delegate = self
    categoriesTableView.dataSource = self
    contentsTableView.delegate = self
    contentsTableView.dataSource = self
  }

  // MARK: - UITableViewDataSource Methods

  func numberOfSections(in tableView: UITableView) -> Int {
    1
  }

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if tableView == categoriesTableView {
      return dataSource?.numberOfCategories() ?? 0
    } else if tableView == contentsTableView {
      guard let selectedIndex = selectedCategoryIndex else { return 0 }
      return dataSource?.categoryAt(index: selectedIndex).contents.count ?? 0
    }
    return 0
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    if tableView == categoriesTableView {
      let category = dataSource?.categoryAt(index: indexPath.row)
      cell.textLabel?.text = category?.name
    } else if tableView == contentsTableView {
      guard let selectedIndex = selectedCategoryIndex else { return cell }
      let content = dataSource?.categoryAt(index: selectedIndex).contents[indexPath.row]
      cell.textLabel?.text = content
    }
    return cell
  }

  // MARK: - UITableViewDelegate Methods

  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if tableView == categoriesTableView {
      selectedCategoryIndex = indexPath.row
      contentsTableView.reloadData()
      delegate?.didSelectCategory(at: indexPath.row)
    } else if tableView == contentsTableView {
      guard let selectedCategoryIndex = selectedCategoryIndex else { return }
      delegate?.didSelectContent(at: selectedCategoryIndex, contentIndex: indexPath.row)
    }
  }
}
